class Image {
  constructor($, options) {
    this.$dom = $(options.dom);
    this.$imgC = this.$dom.find(".imgC");
    this.$imgCItem = this.$imgC.find(".itemImg");
    this.sliderW = this.$dom.width();
    this.indicatorItem = this.$dom
      .find(".car-indicator")
      .find(".indicator-item");
    this.speed = options.speed;
    this.curIdx = 0;
    this.timer = null;
    this.init();
  }
  init() {
    this.cloneItem();
    this.playAuto();
    this.bindEvent();
  }
  cloneItem() {
    this.$imgC.append(this.$imgCItem.eq(0).clone());
  }
  bindEvent() {
    this.$dom.on("mouseover", { event: "in" }, $.proxy(this.mousemove, this));
    this.$dom.on("mouseout", { event: "out" }, $.proxy(this.mousemove, this));
    this.$dom.on("click", $.proxy(this.mouseClick, this));
  }
  mousemove(e) {
    let ev = e.data.event;
    if (ev === "in") {
      clearInterval(this.timer);
    } else {
      this.playAuto();
    }
  }
  mouseClick(ev) {
    const e = ev || window.event,
      tar = e.target || e.srcElement,
      tagName = tar.tagName.toLowerCase();
    if (tagName === "button") {
      const dir = tar.dataset.dir;
      this.changeIndex(dir);
    } else if (tagName === "i") {
      this.curIdx = $(tar).index();
      this.pageChange("", this.curIdx, ".5s");
    }
  }
  playAuto() {
    this.timer = setInterval(() => {
      this.run();
    }, this.speed);
  }
  run() {
    this.changeIndex("next");
  }
  changeIndex(dir) {
    let timer;
    switch (dir) {
      case "next":
        if (this.curIdx === this.$imgCItem.length) {
          this.curIdx = 1;
          this.pageChange("", this.curIdx, "initial");
          timer = setTimeout(() => {
            this.pageChange("", this.curIdx, ".5s");
            clearInterval(timer);
          }, 100);
        } else {
          this.curIdx++;
          this.pageChange("", this.curIdx, ".5s");
        }
        break;
      case "prev":
        if (this.curIdx === 0) {
          this.curIdx = this.$imgCItem.length - 1;
          this.pageChange("length", this.curIdx, "initial");
          timer = setTimeout(() => {
            this.pageChange("", this.curIdx, ".5s");
            clearInterval(timer);
          }, 100);
        } else {
          this.curIdx--;
          this.pageChange("", this.curIdx, ".5s");
        }
        break;
      default:
        break;
    }
  }
  pageChange(tpye, index, duration) {
    const num = tpye === "length" ? this.$imgCItem.length : index;
    this.$imgC.css({
      transform: `translate3d(${-this.sliderW * num}px,0px,0px)`,
      transitionDuration: duration,
    });
    this.changeItem(index);
  }
  changeItem(index) {
    this.indicatorItem
      .eq(index)
      .addClass("active")
      .siblings(".indicator-item")
      .removeClass("active");
  }
}

export { Image };
